import datetime
import requests
import json
import time
from typing import Dict, Optional
from sqlalchemy.orm import Session

from core.logger import logger
from common.welab_doris import WelabDoris
from common.utils import CommonTimeUtils
from common.notice_tools import NoticeTools

from setting import config


class MonitorDorisHttpCheckHandler():
    """  MonitorDorisHttpCheck Handler
    """
    def __init__(self):
        self.welab_doris = WelabDoris()
        self.notice_tools = NoticeTools()
        self.doris_table = config.DORIS_HTTP_TABLE
        self.wechatbot_group_id = "cd869b9f-0a7c-4ffa-8768-eb74749702f0"



    def alert_to_notice(self, db: Session, alarm_info: dict):
        """
        发送企业微信群消息
        """
        notice_msg_markdown = f"网关日志http状态码监控\n " \
        f"<font color=\"comment\">告警时间 </font>:   <font color=\"comment\">{alarm_info['cst_begin_time']}~{alarm_info['cst_end_time']}</font>\n " \
        f"<font color=\"comment\">告警信息 </font>:   <font color=\"warning\">{alarm_info['alarm_message']}</font>\n " \
        f"<font color=\"comment\">状态码1XX</font>:   <font color=\"info\">{alarm_info['1xx']}</font>\n " \
        f"<font color=\"comment\">状态码2XX</font>:   <font color=\"info\">{alarm_info['2xx']}</font>\n " \
        f"<font color=\"comment\">状态码3XX</font>:   <font color=\"info\">{alarm_info['3xx']}</font>\n " \
        f"<font color=\"comment\">状态码4XX</font>:   <font color=\"warning\">{alarm_info['4xx']}</font>\n " \
        f"<font color=\"comment\">状态码5XX</font>: `{alarm_info['5xx']}`\n "\
        f"<font color=\"comment\">状态码404</font>:   <font color=\"warning\">{alarm_info['404']}</font>\n " \
        f"<font color=\"comment\">状态码500</font>:   <font color=\"warning\">{alarm_info['500']}</font>\n " \
        f"<font color=\"comment\">状态码502</font>:   <font color=\"warning\">{alarm_info['502']}</font>\n "
        
        # 发送到大群
        result = self.notice_tools.send_wechatbot(self.wechatbot_group_id, notice_msg_markdown)
        if not result:
            logger.error(f"send wechat bot failed")
            return False
        
        logger.info(f"send wechat bot success")
        return True
    
    
    
    def http_code_callback(self, code: str):
        """
        状态异常回调函数, 处理异常客户ip地址
        """
        headers = {
            "Content-Type": "application/json",
        }
        url = f"http://192.168.42.21:8088/v1/status?code={code}"
        try:
            # 回调接口
            req = requests.get(url=url, headers=headers, timeout=5)
            if req.status_code != 200:
                logger.error("http code callback failed")
                return False
        except Exception as e:
            logger.error(f"http code callback error: {e}")
            return False
        
        logger.info(f"http code callback:{code} success")
        return True
            

    
    
    def task_http_check_handle(self, db: Session, interval_min: int):
        """
        从doris数据库获取接口的状态码信息保存到mysql数据库的任务处理
        """
        # 获取搜索时间段
        # 实际查询是延后1分钟查询历史日志
        delay_min = 1
        now = datetime.datetime.now()
        cst_begin_time = (now - datetime.timedelta(minutes=interval_min+delay_min)).strftime("%Y-%m-%d %H:%M:%S")
        cst_end_time = (now - datetime.timedelta(minutes=delay_min)).strftime("%Y-%m-%d %H:%M:%S")
        
        alarm_info = {
            "cst_begin_time": cst_begin_time,
            "cst_end_time": cst_end_time,
            "alarm_message": "",
            "1xx": 0,"2xx": 0,"3xx": 0,"4xx": 0,"5xx": 0,"404": 0,"500": 0,"502": 0,
        }
        
        # 获取所有http状态聚合的统计
        result, datas = self.welab_doris.get_http_all_agg(self.doris_table, cst_begin_time, cst_end_time)
        if not result:
            logger.error(f"get all http code agg failed")
            return False
        
        # 判断告警信息
        alarm_message = []
        for data in datas:
            alarm_info.update({data["response_group"]: data["total_count"]})
            
            if data["response_group"] == "404" and data["total_count"] >= 150:
                alarm_message.append("404状态码 >= 150")
                self.http_code_callback("404")
                continue
            
            if data["response_group"] == "500" and data["total_count"] >= 30:
                alarm_message.append("500状态码 >= 30")
                self.http_code_callback("500")
                continue
            
            if data["response_group"] == "502" and data["total_count"] >= 150:
                alarm_message.append("502状态码 >= 150")
                self.http_code_callback("502")
                continue
            
            if data["response_group"] == "5xx" and data["total_count"] >= 30:
                alarm_message.append("5xx状态码 >= 30")
                continue
            
        if len(alarm_message) == 0:
            logger.info("http code check condition is 0, no need to alarm")
            return True
        
        # 直接发送告警到群里
        alarm_info["alarm_message"] = " , ".join(alarm_message)
        self.alert_to_notice(db, alarm_info)
        
        logger.info("all http code check success")
        return True
            
            
        
    
    
def main():
    from common.database import SessionLocal
    session = SessionLocal()
    interval_min = 5200


    monitor_doris_http_check_handler = MonitorDorisHttpCheckHandler()
    result = monitor_doris_http_check_handler.task_http_check_handle(session, interval_min)
    print(result)



if __name__ == "__main__":
    main()

            

